package cn.wlinker.driver.modbus.tcp.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.wlinker.driver.modbus.tcp.domain.ModbusBean;
import cn.wlinker.driver.modbus.tcp.domain.ModbusResItem;

import java.util.LinkedList;
import java.util.List;

/**
 * modbus响应工具类
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/10/12
 */
public class ModbusResultUtils {

    private static List<Byte> getByteList(boolean[] booleans) {
        List<Byte> byteList = new LinkedList<>();
        for (boolean aBoolean : booleans) {
            byteList.add(aBoolean ? (byte) 1 : (byte) 0);
        }
        return byteList;
    }

    private static List<Short> getShortList(short[] shorts) {
        List<Short> shortList = new LinkedList<>();
        for (short aShort : shorts) {
            shortList.add(aShort);
        }
        return shortList;
    }

    public static List<ModbusResItem> getItemList(ModbusBean modbusBean, boolean[] booleans) {
        Integer slaveId = modbusBean.getSlaveId();
        Integer functionType = modbusBean.getFunctionType();
        Integer offset = modbusBean.getAddress();
        List<Byte> byteList = getByteList(booleans);
        return getItemList(slaveId, functionType, offset, byteList, 1);
    }

    public static List<ModbusResItem> getItemList(ModbusBean modbusBean, List<Number> numbers, Integer registerCount) {
        Integer slaveId = modbusBean.getSlaveId();
        Integer functionType = modbusBean.getFunctionType();
        Integer offset = modbusBean.getAddress();
        return getItemList(slaveId, functionType, offset, numbers, registerCount);
    }

    public static List<ModbusResItem> getItemList(ModbusBean modbusBean, Number number) {
        ModbusResItem modbusResItem = new ModbusResItem();
        modbusResItem.setSlaveId(modbusBean.getSlaveId());
        modbusResItem.setFunctionType(modbusBean.getQuantity());
        modbusResItem.setAddress(modbusBean.getAddress());
        modbusResItem.setValue(number.toString());
        return CollUtil.newLinkedList(modbusResItem);
    }


    private static <T> List<ModbusResItem> getItemList(Integer slaveId, Integer functionType, Integer offset, List<T> list, Integer registerCount) {
        List<ModbusResItem> resBeanList = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            T value = list.get(i);
            ModbusResItem modbusResItem = new ModbusResItem();
            modbusResItem.setSlaveId(slaveId);
            modbusResItem.setFunctionType(functionType);
            Integer currentAddress = offset + i * registerCount;
            modbusResItem.setAddress(currentAddress);
            modbusResItem.setValue(StrUtil.toString(value));
            resBeanList.add(modbusResItem);
        }
        return resBeanList;
    }


}
